package Viewer;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;

import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

/**
 * This class implements the track shifitng. The panel contains comboxes for each track to
 * shift the track positions and anchor track to other ones-
 * @author Stefan Lorenz<br>
 * <br>29.11.2012
 */
@SuppressWarnings("serial")
public class TrackShifting extends JPanel implements ChangeListener {

    private Viewer viewer;
    private JSpinner spinner;
    @SuppressWarnings("rawtypes")
    private JComboBox anchor;
    private int index;

    /**
     * Constructor of the track shifting panel
     * @param index index of the track
     * @param viewer viewer of the genescapes session
     */
    @SuppressWarnings("unchecked")
    public TrackShifting(int index, Viewer viewer) {
	this.index = index;
	this.setLayout(new GridBagLayout());
	this.setOpaque(false);
	JPanel panel = new JPanel();
	panel.setOpaque(false);
	this.viewer = viewer;
	this.spinner = new JSpinner();
	this.spinner.setPreferredSize(new Dimension(125, 25));
	this.spinner.setMinimumSize(new Dimension(125, 25));

	this.anchor = new JComboBox<Integer>();
	for (int i = 0; i < 16; i++) {
	    this.anchor.addItem(i);
	}
	this.anchor.setSelectedIndex(this.index);
	panel.add(this.spinner);
	panel.add(this.anchor);
	panel.setOpaque(false);
	TitledBorder titledBorder = BorderFactory.createTitledBorder(null, "Track: " + String.valueOf(index), TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.CENTER, new Font("Arial", Font.BOLD, 12), Color.BLACK);
	panel.setBorder(titledBorder);

	this.add(panel);

	this.spinner.addChangeListener(this);
    }

    /**
     * Updates the position in the track position line
     * @param position
     *            position for spinnner
     */
    public void refreshTrackPositionLine(int position) {
	this.spinner.setValue(position);
    }

    /* (non-Javadoc)
     * @see javax.swing.event.ChangeListener#stateChanged(javax.swing.event.ChangeEvent)
     */
    @Override
    public void stateChanged(ChangeEvent e) {
	for (int i = 0; i < 16; i++) {
	    if (this.viewer.getTrackPositionLines(i).getAnchor() == this.getAnchor())
		this.viewer.setPositionOfBrowser(this.index, Integer.parseInt(this.spinner.getValue().toString()));
	}
	this.viewer.getDrawPanel().repaint();
    }

    /**
     * Returns the anchored index of the track
     * @return the anchored index of the track
     */
    public int getAnchor() {
	return this.anchor.getSelectedIndex();
    }
}
